import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { ApiAdapter, AdapterRegistry, ApiProvider, TargetProvider } from '../interfaces/api-adapter.interface';

/**
 * 适配器注册表服务
 * 管理所有 API 适配器的注册、查找和生命周期
 */
@Injectable()
export class AdapterRegistryService implements AdapterRegistry, OnModuleInit {
  private readonly logger = new Logger(AdapterRegistryService.name);
  private readonly adapters = new Map<string, ApiAdapter>();

  async onModuleInit() {
    this.logger.log('Adapter registry initialized');
  }

  /**
   * 注册适配器
   */
  register(adapter: ApiAdapter): void {
    const key = this.getAdapterKey(adapter.provider, adapter.target);
    
    if (this.adapters.has(key)) {
      this.logger.warn(`Adapter for ${adapter.provider} -> ${adapter.target} already registered, overwriting`);
    }
    
    this.adapters.set(key, adapter);
    this.logger.log(`Registered adapter: ${adapter.provider} -> ${adapter.target}`);
  }

  /**
   * 获取指定的适配器
   */
  getAdapter(provider: ApiProvider, target: TargetProvider): ApiAdapter | null {
    const key = this.getAdapterKey(provider, target);
    const adapter = this.adapters.get(key);
    
    if (!adapter) {
      this.logger.warn(`No adapter found for ${provider} -> ${target}`);
      return null;
    }
    
    return adapter;
  }

  /**
   * 获取所有适配器
   */
  getAllAdapters(): ApiAdapter[] {
    return Array.from(this.adapters.values());
  }

  /**
   * 按源 API 提供商获取适配器
   */
  getAdaptersByProvider(provider: ApiProvider): ApiAdapter[] {
    return this.getAllAdapters().filter(adapter => adapter.provider === provider);
  }

  /**
   * 按目标 API 提供商获取适配器
   */  
  getAdaptersByTarget(target: TargetProvider): ApiAdapter[] {
    return this.getAllAdapters().filter(adapter => adapter.target === target);
  }

  /**
   * 检查是否支持指定的转发路径
   */
  isSupported(provider: ApiProvider, target: TargetProvider): boolean {
    return this.getAdapter(provider, target) !== null;
  }

  /**
   * 获取所有支持的转发路径
   */
  getSupportedRoutes(): Array<{ provider: ApiProvider; target: TargetProvider }> {
    return this.getAllAdapters().map(adapter => ({
      provider: adapter.provider,
      target: adapter.target
    }));
  }

  /**
   * 批量健康检查所有适配器
   */
  async checkAllAdaptersHealth(): Promise<Map<string, any>> {
    const healthResults = new Map<string, any>();
    
    for (const [key, adapter] of this.adapters) {
      try {
        const health = await adapter.checkHealth();
        healthResults.set(key, health);
      } catch (error) {
        this.logger.error(`Health check failed for adapter ${key}: ${error.message}`);
        healthResults.set(key, {
          status: 'unhealthy',
          provider: adapter.provider,
          target: adapter.target,
          error: error.message,
          lastCheck: new Date()
        });
      }
    }
    
    return healthResults;
  }

  /**
   * 取消注册适配器
   */
  unregister(provider: ApiProvider, target: TargetProvider): boolean {
    const key = this.getAdapterKey(provider, target);
    const removed = this.adapters.delete(key);
    
    if (removed) {
      this.logger.log(`Unregistered adapter: ${provider} -> ${target}`);
    } else {
      this.logger.warn(`Adapter ${provider} -> ${target} not found for unregistration`);
    }
    
    return removed;
  }

  /**
   * 清空所有适配器
   */
  clear(): void {
    const count = this.adapters.size;
    this.adapters.clear();
    this.logger.log(`Cleared ${count} adapters from registry`);
  }

  /**
   * 获取注册统计信息
   */
  getStats(): {
    totalAdapters: number;
    providerCounts: Record<string, number>;
    targetCounts: Record<string, number>;
  } {
    const allAdapters = this.getAllAdapters();
    const providerCounts: Record<string, number> = {};
    const targetCounts: Record<string, number> = {};
    
    allAdapters.forEach(adapter => {
      providerCounts[adapter.provider] = (providerCounts[adapter.provider] || 0) + 1;
      targetCounts[adapter.target] = (targetCounts[adapter.target] || 0) + 1;
    });
    
    return {
      totalAdapters: allAdapters.length,
      providerCounts,
      targetCounts
    };
  }

  /**
   * 生成适配器的唯一键
   */
  private getAdapterKey(provider: ApiProvider, target: TargetProvider): string {
    return `${provider}->${target}`;
  }
}